﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MyPhotoIndex.Controls;

namespace MyPhotoIndex.Settings
{
    public partial class ProxySettingsForm : FormTemplate
    {
        public ProxySettingsForm()
        {
            InitializeComponent();

            useProxyCheckBox.Checked = ApplicationSettings.Default.WebProxySettings.UseProxy;
            proxyUrlTextBox.Text = ApplicationSettings.Default.WebProxySettings.Url;
            proxyPortTextBox.Text = ApplicationSettings.Default.WebProxySettings.Port.ToString();
            proxyUserTextBox.Text = ApplicationSettings.Default.WebProxySettings.UserName;
            proxyUserTextBox.Text = ApplicationSettings.Default.WebProxySettings.Password;

            ToggleStates();
            useProxyCheckBox.CheckedChanged += new EventHandler(useProxyCheckBox_CheckedChanged);
            proxyPortTextBox.KeyPress += new KeyPressEventHandler(proxyPortTextBox_KeyPress);
        }

        void proxyPortTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            } 
        }

        void useProxyCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            ToggleStates();
        }

        private void ToggleStates()
        {
            Control[] controls = new Control[]{label1, label2, label3, label4, proxyUrlTextBox, proxyPortTextBox
                                                , proxyUserTextBox, proxyPasswordTextBox};

            foreach (Control control in controls)
            {
                control.Visible = useProxyCheckBox.Checked;
            }
        }

        protected override void OkButton_Click(object sender, EventArgs e)
        {
            ApplicationSettings.Default.WebProxySettings.UseProxy = useProxyCheckBox.Checked;
            ApplicationSettings.Default.WebProxySettings.Url = proxyUrlTextBox.Text;
            ApplicationSettings.Default.WebProxySettings.Port = Convert.ToInt32(proxyPortTextBox.Text);
            ApplicationSettings.Default.WebProxySettings.UserName = proxyUserTextBox.Text;
            ApplicationSettings.Default.WebProxySettings.Password = proxyUserTextBox.Text;

            ApplicationSettings.Default.Save();
            ApplicationSettings.Default.WebProxySettings.RefreshProxySettings();

            base.OkButton_Click(sender, e);
        }

    }
}
